﻿var OfferModel = function (offers) {
    var self = this;
    self.currentItem = ko.observable('');
    self.sortDirection = ko.observable(true);
    self.offers = ko.observableArray(offers);
    var privateOffers = offers;
    self.columnNames = ko.observableArray([
            'Информация за шофьора:',
            'Тръгване от:',
            'Пристигане в:',
            'Дата',
            'Цена',
            'Опции',
            ''
    ]);
    self.addOffer = function () {
        self.offers.push({
            driver: "",
            price: "",
            trip: "",
        });
    };

    self.removeOffer = function (offer) {
        self.offers.remove(offer);
    };


    function getValueOfCurrentColumn(offer, columnId) {
        var value;
        switch (columnId) {
            case 'Информация за шофьора:':
                {
                    value = offer.driver.fname + ' ' + offer.driver.lname + ' ' + offer.driver.email + ' ' + offer.driver.phone;
                    break;
                }
            case 'Тръгване от:':
                {
                    value = offer.trip.from;
                    break;
                }
            case 'Пристигане в:':
                {
                    value = offer.trip.to;
                    break;
                }
            case 'Дата':
                {
                    value = offer.trip.dateOfDeparture;
                    break;
                }
            case 'Цена':
                {
                    if (offer.price.value === undefined || offer.price.value === "") {
                        value = 0;
                    }
                    else {
                        value = parseFloat(offer.price.value);
                    }
                    break;
                }
            default:
                {
                    value = undefined;
                    break;
                }
        }

        return value;
    }

    function sort(columnId) {
        var i, j;
        var currentMin;

        for (i = 0; i < privateOffers.length - 1; i++) {
            currentMin = privateOffers[i];
            var indexOfCurrentMin = i;
            var firstValue = getValueOfCurrentColumn(privateOffers[i], columnId);
            for (j = i + 1; j < privateOffers.length; j++) {
                var secondValue = getValueOfCurrentColumn(privateOffers[j], columnId);
                if (firstValue > secondValue) {
                    firstValue = secondValue;
                    indexOfCurrentMin = j;
                }
            }
            if (i != indexOfCurrentMin) {
                var temp = privateOffers[i];
                privateOffers[i] = privateOffers[indexOfCurrentMin];
                privateOffers[indexOfCurrentMin] = temp;
            }
        }
    }

    function reverse() {
        var i;
        var oldValues = [];

        for (i = privateOffers.length - 1; i >= 0; i--) {
            oldValues.push(privateOffers[i]);
        }

        privateOffers = oldValues;
    }

    self.sortColumn = function (item) {
        if (item == self.currentItem()) {
            self.sortDirection(!self.sortDirection())
        } else {
            self.currentItem(item);
            self.sortDirection(true)
        }
        if (self.sortDirection()) {
            sort(item);
            self.offers(privateOffers);
        } else {
            reverse();
            self.offers(privateOffers);
        }
    };

    self.printOffer = function (offer) {

        var newWindow = $("<div class='offerInfo'></div>");
        newWindow.attr("id", "tick-offer");

        var innerText = '<ul><h3>Информация за шофьора:</h3><li>Име: '
            + (offer.driver.fname ? offer.driver.fname : "Няма") + '</li>';
        innerText += '<li>Фамилия: ' + (offer.driver.lname ? offer.driver.lname : "Няма") + '</li>';
        innerText += '<li>E-mail: ' + (offer.driver.email ? offer.driver.email : "Няма") + '</li>';
        innerText += '<li>Телефон: ' + (offer.driver.phone ? offer.driver.phone : "Няма") + '</li>';
        innerText += '<li>Възраст: ' + (offer.driver.age ? offer.driver.age : "Няма") + '</li>';
        innerText += '<li>Пол: ' + (offer.driver.gender ? offer.driver.gender : "Няма") + '</li>';
        innerText += '<li>Рейтинг: ' + (offer.driver.rating ? offer.driver.rating : "Няма") + '</li></ul>';
        innerText += '<ul><h3>Кола:</h3><li>Тип: ' + (offer.driver.vehicle.type ?
            offer.driver.vehicle.type : "Няма") + '</li>';
        innerText += '<li>Марка: ' + (offer.driver.vehicle.brand ?
            offer.driver.vehicle.brand : "Няма") + '</li>';
        innerText += '<li>Година:' + (offer.driver.vehicle.year ?
            offer.driver.vehicle.year : "Няма") + '</li>';
        innerText += '<li>Свободни места: ' + (offer.driver.vehicle.seats ?
            offer.driver.vehicle.seats : "Няма") + '</li>';
        innerText += '<li>Разход(л./100км.): ' + (offer.driver.vehicle.fuelConsumption ?
            offer.driver.vehicle.fuelConsumption : "Няма") + '</li></ul>';
        innerText += '<ul><h3>Информация за пътуването:</h3><li>Начална точка: ' +
           (offer.trip.from ? offer.trip.from : "Няма") + '</li>';
        innerText += '<li>Крайна точка: ' + (offer.trip.to ? offer.trip.to : "Няма") + '</li>';
        innerText += '<li>Дата: ' + (offer.trip.dateOfDeparture ? offer.trip.dateOfDeparture : "Няма") + '</li></ul>';
        innerText += '<ul><h3>Информация за цената:</h3><li>' + (offer.price.value ? offer.price.value : 'Няма') + ' ' +
            (offer.price.currency ? offer.price.currency : '') + '</li>';
        innerText += '<li>Изисквания на шофьора: ' + (offer.driver.requirements ?
            offer.driver.requirements : "Няма") + '</li></ul>';

        newWindow.html(innerText);
        $("#header").append(newWindow);

        //$("#undo")
        //           .bind("click", function () {
        //               $("#window").data("kendoWindow").open();
        //               $("#undo").hide();
        //           });

        if (!newWindow.data("kendoWindow")) {
            newWindow.kendoWindow({
                title: "Информация за офертата",
                width: "600px",
                height: "400px",
                scrollable: "auto",
            });
        }
        //$("#tick-offer").append(table);
    };

    self.save = function (form) {
        alert("Could now transmit to server: " + ko.utils.stringifyJson(self.offers));
        // To actually transmit to server as a regular form post, write this: ko.utils.postJson($("form")[0], self.offers);
    }

    self.toString = function () {
        var i;
        var stringBuilder = "";
        for (i = 0; i < privateOffers.length; i++) {
            stringBuilder += privateOffers[i].toString() + "\n";
        }
        return stringBuilder;
    };
};

var get = new dbModule.Get();

get.offerByConditions(tripInfo, function (data) {

    var allOffers = [];
    for (var i = 0; i < data.length; i++) {
        var obj = new TripDetails.Offer(data[i].driver, data[i].price, data[i].trip);
        JSON.stringify(obj);
        allOffers.push(obj);
        allOffers.sort();
    }
    var viewModel = new OfferModel(allOffers);

    ko.applyBindings(viewModel);
});